#!/bin/bash
set -e
set -x
MYDIR="${0%/*}"
cd "$MYDIR/.."
source "recipes/common.sh"


# RECIPE START ncurses

# XXX: author bumps SONAME for no good reason
NCURSES_ABI_VERSION=5

rm -rf build/ncurses
mkdir -p build/ncurses
cd build/ncurses
../../ncurses/configure \
	${CONFIGURE_ARGS} \
	--with-shared \
	${NCURSES_ABI_VERSION+--with-abi-version=$NCURSES_ABI_VERSION} \
	--enable-widec \
	--with-termlib=tinfo \
	--enable-pc-files \
	--with-pkg-config-libdir=${prefix}/${target_libdir}/pkgconfig \
	--without-debug \
	--without-ada \
	--without-cxx-bindings \
	--enable-overwrite \
	--disable-stripping \
	--disable-db-install \
	--without-manpages \
	--with-build-cc=gcc

# XXX: building terminfo files requires ncurses programs, and we can't
# run host binaries when cross-compiling. Hence --disable-db-install above...
cd ../..
make_build build/ncurses
ln -sf ncursesw.pc "${stage}${prefix}/${target_libdir}/pkgconfig/ncurses.pc"

# ... however ncurses programs are a bit broken without terminfo.
# Therefore build a temporary ncurses for $BUILD and extract terminfo
# from there.

save_CFLAGS="$CFLAGS"
save_CPPFLAGS="$CPPFLAGS"
save_LDFLAGS="$LDFLAGS"
export CFLAGS='-O2 -g'
unset CPPFLAGS
unset LDFLAGS

mkdir -p build/ncurses-native
cd build/ncurses-native
../../ncurses/configure \
	--host=${BUILD} \
	--build=${BUILD} \
	--prefix=$prefix \
	--disable-shared \
	--enable-widec \
	--with-termlib=tinfo \
	--disable-pc-files \
	--without-debug \
	--without-ada \
	--without-cxx-bindings \
	--enable-overwrite \
	--disable-stripping \
	--without-tests \
	--without-manpages

make -j${JOBS}
make -j${JOBS} install DESTDIR=`pwd`/inst
mkdir -p -m 755 "${stage}${prefix}/share"
cp -a inst${prefix}/share/terminfo "${stage}${prefix}/share/"

# Install native ncurses headers/libraries.
# Required for building native {s,c}fdisk.
mkdir -p -m755 "${xtools}${build_prefix}"
set -o pipefail
tar -c -f - -C inst${prefix} \
	include \
	lib/libtinfo.a \
	lib/libncursesw.a \
	| \
tar -x -v -f - -C "${xtools}${build_prefix}"

cd ../..
rm -rf build/ncurses-native

export CFLAGS="$save_CFLAGS"
export CPPFLAGS="$save_CPPFLAGS"
export LDFLAGS="$save_LDFLAGS"

# RECIPE END ncurses
